package com.itheima.tliaswebmanagement.interceptor;

import com.alibaba.fastjson2.JSONObject;
import com.itheima.tliaswebmanagement.pojo.Result;
import com.itheima.tliaswebmanagement.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.io.PrintWriter;

@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    public LoginCheckInterceptor() {
        log.info("拦截器已被创建...");
    }

    /**
     * 目标资源方法执行前执行
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle...");
        String requestURL = request.getRequestURL().toString();// 获取请求的资源路径
        log.info("访问资源:{}", requestURL);
        String jwt = request.getHeader("token");// 尝试获取请求头中的"token"字段值,得到jwt令牌
        if (!StringUtils.hasLength(jwt)) {
            // 如果"token"没有长度,意味着没有令牌
            Result notLogin = Result.error("NOT_LOGIN");
            PrintWriter writer = response.getWriter();
            writer.write(JSONObject.toJSONString(notLogin));//响应用户未登录的信息信息,这些信息遵循API需求文档
            return false;// 拒绝放行
        }
        // 至此,意味着请求参数中携带了令牌
        try {
            JwtUtils.parseJwt(jwt);
        } catch (Exception e) {
            // 如果捕获到异常,意味着令牌被篡改或已失效
            Result notLogin = Result.error("NOT_LOGIN");
            PrintWriter writer = response.getWriter();
            writer.write(JSONObject.toJSONString(notLogin));
            return false;
        }
        return true;
    }

    /**
     * 目标资源方法执行后执行
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle...");
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    /**
     * 视图渲染完毕后执行，最后执行
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion...");
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
